﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;

namespace WindowsFormsApplication1
{
    public partial class EKMSearch : Form
    {
        public Form1 frm1;

        #region Function Keys
        protected override bool ProcessDialogKey(Keys keyData)
        {
            switch (keyData)
            {
                case Keys.Escape:
                    this.Close();
                    break;
            }

            return base.ProcessDialogKey(keyData);
        }
        #endregion
        #region Borderless Window
        protected override void WndProc(ref Message m)
        {
            // Let the base class have first crack
            base.WndProc(ref m);
            int WM_NCHITTEST = 0x84; // winuser.h
            // If the user clicked on the client area,
            // ask the OS to treat it as a click on the caption
            if (m.Msg != WM_NCHITTEST) return;
            int HTCLIENT = 1;
            int HTCAPTION = 2;
            if (m.Result.ToInt32() == HTCLIENT)
                m.Result = (IntPtr)HTCAPTION;
        }
        #endregion

        public EKMSearch()
        {
            InitializeComponent();
        }

        private void EKMSearch_Load(object sender, EventArgs e)
        {
            cbDomain.SelectedItem = (Object)"US";
           // frm1.cajaURL.Text = ;
        }

        private void bnSearch_Click(object sender, EventArgs e)
        {
            dGrid.Columns.Clear();

            List<Uri> links = new List<Uri>();
            String termino_busqueda = cajaSearch.Text;
            String busqueda = "http://ekmswgi.amer.quick2know.eds.com/EKMS/Search/default.asp?SearchType=AllWords+&ShowSummary=True&QU=" + termino_busqueda + "&SCOPE=%2FEKMS%2FWGI_Delphi_" + cbDomain.SelectedItem.ToString() + "&submit=Go&Action=Search";
            
            System.Net.WebClient webClient = new System.Net.WebClient();
            string strSource = webClient.DownloadString(busqueda);
            webClient.Dispose();

            links = findUris(strSource);
            findSummary(strSource);

            int x = 0, n = 0;
            dGrid.Columns.Add("TITLE", "TITLE");
            dGrid.Columns.Add("SUMMARY", "SUMMARY");
            dGrid.Columns.Add("URL", "URL");
            foreach (Uri url in links)
            {
                n = dGrid.Rows.Add();
                dGrid.Rows[n].Cells["TITLE"].Value = name[x].ToString();
                dGrid.Rows[n].Cells["SUMMARY"].Value = sum[x].ToString();
                dGrid.Rows[n].Cells["URL"].Value = url.AbsoluteUri;

                x++;
            }
        }

        private List<String> name = new List<String>();
        private List<String> sum = new List<String>();

        List<Uri> findUris(string message)
        {
            string anchorPattern = "<a.*href=[\"'](?<url>[^\"]+[.\\s]*)[\"'].*>(?<name>[^<]+[.\\s]*)</a>";
            MatchCollection matches = Regex.Matches(message, anchorPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
            if (matches.Count > 0)
            {
                name.Clear();                
                List<Uri> uris = new List<Uri>();
                
                foreach (Match m in matches)
                {
                    string url = m.Groups["url"].Value;
                    string nam = m.Groups["name"].Value;                    
                    Uri testUri = null;
                    if (Uri.TryCreate(url, UriKind.Absolute, out testUri))
                    {
                        uris.Add(testUri);
                        name.Add(nam);
                    }
                }
                return uris;
            }
            return null;
        }

        void findSummary(string message)
        {
            string anchorPattern = "<b>Summary:</b> (?<sum>[^\"]+[.\\s]*)<br>";
            MatchCollection matches = Regex.Matches(message, anchorPattern, RegexOptions.IgnorePatternWhitespace | RegexOptions.IgnoreCase | RegexOptions.Multiline | RegexOptions.Compiled);
            if (matches.Count > 0)
            {
                sum.Clear();

                foreach (Match m in matches)
                {
                    sum.Add(m.Groups["sum"].Value);
                }
            }
        }

        private void dGrid_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyValue == 13)
            {
                String url = dGrid.CurrentRow.Cells[2].Value.ToString();
                System.Diagnostics.Process process = new System.Diagnostics.Process();
                process.StartInfo.UseShellExecute = true;
                process.StartInfo.FileName = url;
                process.Start();
                frm1.cajaURL.Text = url;                
            }
        }

    }
}
